using System;
using System.Linq;
using Widgetsphere.Core.DataAccess;
using System.Collections.Generic;

namespace Acme.Sales
{
	/// <summary>
	/// This is the base class for all custom paging objects
	/// </summary>
	[Serializable]
	public partial class PagingBase<T> : IPagingObject
		where T : IPagingFieldItem
	{
		#region Class Members

		private int _pageIndex = 1;
		private int _recordsperPage = 10;
		private List<T> _orderByList = new List<T>();
		private int _recordCount = 0;

		#endregion

		#region Constructors

		/// <summary>
		/// Creates a paging object
		/// </summary>
		public PagingBase()
			: this(1, 10, default(T))
		{
		}

		/// <summary>
		/// Creates a paging object
		/// </summary>
		/// <param name="pageIndex">The page number to load</param>
		/// <param name="recordsperPage">The number of records per page.</param>
		public PagingBase(int pageIndex, int recordsperPage)
			: this(pageIndex, recordsperPage, default(T))
		{
		}

		/// <summary>
		/// Creates a paging object
		/// </summary>
		/// <param name="pageIndex">The page number to load</param>
		/// <param name="recordsperPage">The number of items per page.</param>
		/// <param name="orderByField">The field on which to sort.</param>
		public PagingBase(int pageIndex, int recordsperPage, T orderByField)
		{
			if (pageIndex < 1) throw new Exception("The PageIndex must be 1 or greater.");
			if (recordsperPage < 1) throw new Exception("The RecordsPerPage must be 1 or greater.");

			_pageIndex = pageIndex;
			_recordsperPage = recordsperPage;
			if (orderByField != null)
				_orderByList.Add(orderByField);
		}

		#endregion

		#region Property Implementations

		/// <summary>
		/// The page number of load.
		/// </summary>
		public int PageIndex
		{
			get { return _pageIndex; }
			set
			{
				if (value < 1) throw new Exception("The PageIndex must be 1 or greater.");
				_pageIndex = value;
			}
		}

		/// <summary>
		/// The number of items per page.
		/// </summary>
		public int RecordsperPage
		{
			get { return _recordsperPage; }
			set
			{
				if (value < 1) throw new Exception("The RecordsperPage must be 1 or greater.");
				_recordsperPage = value;
			}
		}

		/// <summary>
		/// A list of fields on which to sort.
		/// </summary>
		public List<T> OrderByList
		{
			get { return _orderByList; }
		}

		/// <summary>
		/// The total number of non-paged items returned for the search.
		/// </summary>
		public int RecordCount
		{
			get { return _recordCount; }
			set { _recordCount = value; }
		}

		#endregion

		#region IPagingObject Members

		IEnumerable<IPagingFieldItem> IPagingObject.GetOrderByList()
		{
			List<IPagingFieldItem> retval = new List<IPagingFieldItem>();
			foreach (IPagingFieldItem item in this.OrderByList)
			{
				retval.Add(item);
			}
			return retval.AsEnumerable();
		}

		#endregion

	}
}
